package net.sf.midollo.net;

import net.sf.midollo.io.IOStream;
import net.sf.midollo.io.IOStreamConnector;
import net.sf.midollo.io.IOUtils;
import net.sf.midollo.io.DefaultIOStream;
import net.sf.midollo.net.io.HttpIOStream;
import net.sf.midollo.net.io.HttpIOStreamFactory;

import java.net.HttpURLConnection;
import java.net.URL;

public class HttpClient {

	public static final int BUFFER_SIZE = 8 * 1024;

	public static void main(String[] args) {
		try {

			String location = "127.0.0.1:8080";
			String method = "GET";
			for (int idx = 0; idx < args.length; ++idx) {
				if (args[idx].compareTo("-u") == 0) {
					if (++idx < args.length) {
						location = args[idx];
					}
				} else if (args[idx].compareTo("-m") == 0) {
					if (++idx < args.length) {
						method = args[idx];
					}
				}
			}

			URL url = new URL(location);
			IOStream ioClient = new DefaultIOStream(System.in, System.out);

			HttpIOStreamFactory httpIOStreamFactory = new HttpIOStreamFactory(url, method);
			HttpIOStream ioServer = (HttpIOStream)httpIOStreamFactory.open();
			HttpURLConnection connection = ioServer.getHttpURLConnection();

			if (connection.getDoOutput()) {
				IOStream ioRequest = IOUtils.connectRequest(ioClient, ioServer);
				IOStreamConnector connector = new IOStreamConnector(ioRequest, BUFFER_SIZE);
				connector.runConnector();
			}

			if (connection.getDoInput()) {
				IOStream ioResponse = IOUtils.connectResponse(ioClient, ioServer);
				IOStreamConnector connector = new IOStreamConnector(ioResponse, BUFFER_SIZE);
				connector.runConnector();
			}

			ioServer.close();
			ioClient.close();

		} catch (Throwable e) {
			e.printStackTrace();
		}
	}
}
